package com.jxtc.enterprise.employee.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jxtc.enterprise.common.entity.Company;
import com.jxtc.enterprise.common.entity.User;
import com.jxtc.enterprise.common.entity.VipUser;
import com.jxtc.enterprise.common.exception.InsertFailureException;
import com.jxtc.enterprise.common.mapper.CompanyMapper;
import com.jxtc.enterprise.common.mapper.UserMapper;
import com.jxtc.enterprise.common.mapper.VipUserMapper;
import com.jxtc.enterprise.common.utils.QrCodeUtil;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import com.jxtc.enterprise.employee.serviceImpl.VipUserMealServiceImpl;
import com.jxtc.enterprise.employee.vo.req.VipUserRecordCreateReqVo;
import com.jxtc.enterprise.employee.vo.resp.QrCodeCreateRespVo;
import com.jxtc.enterprise.employee.vo.resp.VipUserCarTypeAndVisitorTypeListRespVo;
import com.jxtc.enterprise.employee.vo.resp.VipUserInfoRespVo;
import com.jxtc.enterprise.employee.vo.resp.VipUserOrderCreateRespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/employee/vipUserMeal")
@RequiredArgsConstructor
@Slf4j
public class VipUserMealController {

    /**
     * 二维码扫描后跳转的落地页的基础路径
     */
    @Value("${qrcode.landing.base.url}")
    private String qrCodeLandingBaseUrl;

    private final UserMapper userMapper;
    private final CompanyMapper companyMapper;
    private final VipUserMapper vipUserMapper;

    private final VipUserMealServiceImpl vipUserMealService;

    /**
     * 4.5.1 生成餐券二维码
     */
    @PostMapping("/createQrCode")
    public Result<QrCodeCreateRespVo> createQrCode(@Valid @RequestBody VipUserRecordCreateReqVo reqVo) throws IOException {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, employee mini app view, /createQrCode, req: {}", requestId, JSONObject.toJSONString(reqVo));
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, reqVo.getEmployeePhone())
                .eq(User::getDelFlag, false);
        User employee = userMapper.selectOne(userLambdaQueryWrapper);
        if (employee == null) {
            log.warn("requestId {}, 员工不存在, employeePhone:{}", requestId, reqVo.getEmployeePhone());
            return ResultGenerator.genFailResult("员工不存在");
        }

        // 1. 新增客户信息
        VipUser vipUser = createVipUserRecord(requestId, employee, reqVo);

        // 2. 将新创建的客户记录的 id 作为短码，生成二维码
        String code = vipUser.getId();
        // 例如：https://hr.enterprise.qiyetuancan.com:9095/landing?code=12345678901234567890
        String url = qrCodeLandingBaseUrl + "?code=" + code;

        // 3. 生成二维码为 Base64
        BufferedImage img = QrCodeUtil.generate(url, 360);
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIO.write(img, "PNG", outputStream);
            String base64 = "data:image/png;base64," + Base64Utils.encodeToString(outputStream.toByteArray());

            QrCodeCreateRespVo vo = new QrCodeCreateRespVo();
            vo.setCode(code);
            vo.setUrl(url);
            vo.setQrBase64(base64);

            log.info("requestId {}, employee mini app view, /createQrCode, resp: {}", requestId, JSONObject.toJSONString(vo));
            return ResultGenerator.genSuccessResult(vo);
        }
    }

    private VipUser createVipUserRecord(String requestId, User employee, VipUserRecordCreateReqVo reqVo) {
        VipUser vipUser = new VipUser();
        vipUser.setServiceEmployeeId(employee.getId());
        vipUser.setServiceEmployeeCompanyId(employee.getCompanyId());
        vipUser.setUsername(reqVo.getUsername().trim());
        vipUser.setPhone(reqVo.getPhone().trim());
        vipUser.setFoodCount(reqVo.getFoodCount());
        // 初始剩余可点餐份数与 foodCount 一致
        vipUser.setLeftCreateOrderCount(reqVo.getFoodCount());

        if (StringUtils.hasText(reqVo.getCarNo())) {
            vipUser.setCarNo(reqVo.getCarNo().trim());
        }

        if (StringUtils.hasText(reqVo.getCarType())) {
            vipUser.setCarType(reqVo.getCarType().trim());
        }

        if (StringUtils.hasText(reqVo.getVisitorType())) {
            vipUser.setVisitorType(reqVo.getVisitorType().trim());
        }

        if (!CollectionUtils.isEmpty(reqVo.getImgUrlList())) {
            String vipUserImgUrls = String.join(",", reqVo.getImgUrlList());
            vipUser.setVipUserImgUrls(vipUserImgUrls);
        }

        int insertCount = vipUserMapper.insert(vipUser);
        if (insertCount == 0) {
            log.error("requestId {}, 创建会员用户失败, entity: {}", requestId, JSONObject.toJSONString(vipUser));
            throw new InsertFailureException("创建客户餐失败，请稍后重试");
        }

        return vipUser;
    }


    /**
     * 4.5.2 根据 code 查询餐券信息
     *
     * @param code 二维码链接中包含的 code 值
     */
    @GetMapping("/queryVipUserInfoByCode")
    public Result<VipUserInfoRespVo> queryVipUserInfoByCode(@RequestParam("code") String code) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, employee mini app view, /queryVipUserInfoByCode, code: {}", requestId, code);
        VipUser vipUser = vipUserMapper.selectById(code);
        if (vipUser == null) {
            log.warn("requestId {}, 餐券不存在, code:{}", requestId, code);
            return ResultGenerator.genFailResult("餐券不存在");
        }

        VipUserInfoRespVo vo = new VipUserInfoRespVo();
        vo.setVipUserId(vipUser.getId());
        vo.setUsername(vipUser.getUsername());
        vo.setFoodCount(vipUser.getFoodCount());
        vo.setLeftCreateOrderCount(vipUser.getLeftCreateOrderCount());
        vo.setCarType(vipUser.getCarType());
        vo.setVisitorType(vipUser.getVisitorType());

        log.info("requestId: {}, employee mini app view, /queryVipUserInfoByCode, response: {}", requestId, JSONObject.toJSONString(vo));
        return ResultGenerator.genSuccessResult(vo);
    }


    /**
     * 4.5.3 下单
     *
     * @param vipUserId 客户餐券 ID
     */
    @GetMapping("/createVipUserOrder")
    public Result<VipUserOrderCreateRespVo> createVipUserOrder(@RequestParam("vipUserId") String vipUserId) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, employee mini app view, /createVipUserOrder, vipUserId: {}", requestId, vipUserId);
        int leftCreateOrderCount = vipUserMealService.createVipUserOrder(vipUserId, requestId);
        VipUserOrderCreateRespVo vo = new VipUserOrderCreateRespVo();
        vo.setLeftCreateOrderCount(leftCreateOrderCount);
        log.info("requestId {}, employee mini app view, /createVipUserOrder, response: {}", requestId, JSONObject.toJSONString(vo));
        return ResultGenerator.genSuccessResult(vo);
    }


    /**
     * 4.5.4 通过员工手机号获取客户餐可选择车型列表
     *
     * @param employeePhone 员工手机号
     */
    @Deprecated
    @GetMapping("/queryVipUserCarTypeListByEmployeePhone")
    public Result<List<String>> queryVipUserCarTypeListByEmployeePhone(@RequestParam("employeePhone") String employeePhone) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, employee mini app view, /queryVipUserCarTypeListByEmployeePhone, employeePhone: {}", requestId, employeePhone);

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, employeePhone)
                .eq(User::getDelFlag, false);
        User employee = userMapper.selectOne(userLambdaQueryWrapper);
        if (employee == null) {
            log.warn("requestId {}, /queryVipUserCarTypeListByEmployeePhone, user not exist, employeePhone:{}", requestId, employeePhone);
            return ResultGenerator.genFailResult("员工不存在");
        }

        Company company = companyMapper.selectById(employee.getCompanyId());
        if (company == null) {
            log.warn("requestId {}, /queryVipUserCarTypeListByEmployeePhone, company not exist, employeePhone:{}, companyId: {}", requestId, employeePhone, employee.getCompanyId());
            return ResultGenerator.genFailResult("员工所在公司不存在");
        }

        List<String> voList = Collections.emptyList();
        if (StringUtils.hasText(company.getVipUserCarTypeList())) {
            // 如果数据库中保存的车型列表字符串不为空，则以逗号分割，排序后返回
            voList = Arrays.stream(company.getVipUserCarTypeList().split(","))
                    // 返回的车型列表根据字符串升序排列，不区分大小写
                    .sorted(String::compareToIgnoreCase)
                    .collect(Collectors.toList());
        }

        return ResultGenerator.genSuccessResult(voList);
    }


    /**
     * 4.5.5 通过员工手机号获取客户餐类型信息列表
     *
     * @param employeePhone 员工手机号
     */
    @GetMapping("/queryVipUserTypeListByEmployeePhone")
    public Result<VipUserCarTypeAndVisitorTypeListRespVo> queryVipUserTypeListByEmployeePhone(@RequestParam("employeePhone") String employeePhone) {
        String requestId = UUID.randomUUID().toString();
        log.info("requestId {}, employee mini app view, /queryVipUserTypeListByEmployeePhone, employeePhone: {}", requestId, employeePhone);

        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getPhoneNumber, employeePhone)
                .eq(User::getDelFlag, false);
        User employee = userMapper.selectOne(userLambdaQueryWrapper);
        if (employee == null) {
            log.warn("requestId {}, /queryVipUserTypeListByEmployeePhone, user not exist, employeePhone:{}", requestId, employeePhone);
            return ResultGenerator.genFailResult("员工不存在");
        }

        Company company = companyMapper.selectById(employee.getCompanyId());
        if (company == null) {
            log.warn("requestId {}, /queryVipUserTypeListByEmployeePhone, company not exist, employeePhone:{}, companyId: {}", requestId, employeePhone, employee.getCompanyId());
            return ResultGenerator.genFailResult("员工所在公司不存在");
        }

        List<String> carTypeList = Collections.emptyList();
        if (StringUtils.hasText(company.getVipUserCarTypeList())) {
            // 如果数据库中保存的车型列表字符串不为空，则以逗号分割，排序后返回
            carTypeList = Arrays.stream(company.getVipUserCarTypeList().split(","))
                    // 返回的车型列表根据字符串升序排列，不区分大小写
                    .sorted(String::compareToIgnoreCase)
                    .collect(Collectors.toList());
        }

        List<String> visitorTypeList = Collections.emptyList();
        if (StringUtils.hasText(company.getVipUserVisitorTypeList())) {
            // 如果数据库中保存的访客类型列表字符串不为空，则以逗号分割
            visitorTypeList = Arrays.stream(company.getVipUserVisitorTypeList().split(",")).collect(Collectors.toList());
        }

        VipUserCarTypeAndVisitorTypeListRespVo vo = new VipUserCarTypeAndVisitorTypeListRespVo();
        vo.setVipUserCarTypeList(carTypeList);
        vo.setVipUserVisitorTypeList(visitorTypeList);
        return ResultGenerator.genSuccessResult(vo);
    }
}
